var eb;

window.onload = function init() {
    eb = new EventBus(window.location.protocol + '//' + window.location.hostname + ':' + window.location.port + '/eventbus');

    eb.onclose = function () {
        eb = null;
    };

    eb.onopen = addHandlers;

}

function addHandlers() {

    document.getElementById("imageSrc").addEventListener('change', updateImage);
    document.getElementById("imageSrc").addEventListener('input', updateImage);

    document.getElementById("add-image-btn").addEventListener('click', function (evt) {
        eb.send('vtoons.addImage',
            {
                "imageSrc": document.getElementById("imageSrc").value,
                "imageText": document.getElementById("imageText").value,
                "category": document.getElementById("category").value
            },
            function (err, reply) {
                if (err) {
                    console.error('Failed to add image: ' + err);
                    return;
                }
                showMessage("Image was added!");
                clearForm();
            });
    }, false);
}

function updateImage() {
    document.getElementById("image").src = document.getElementById("imageSrc").value;
}

function showMessage(message) {
    var addImageSection = document.getElementsByClassName("add-image-section")[0];
    var messages = addImageSection.getElementsByClassName("message");
    for (var i = 0; i < messages.length; i++) {
        messages[i].remove();
    }
    var messageSpan = document.createElement("span");
    messageSpan.setAttribute("class", "message message-success");
    messageSpan.innerHTML = message;
    var firstElementInAddImageSection = addImageSection.children[0];
    addImageSection.insertBefore(messageSpan, firstElementInAddImageSection);
    setInterval(function () {
        messageSpan.style.opacity = 0;
    }, 3000);
}

function clearForm() {
    document.getElementById("imageSrc").value = '';
    document.getElementById("imageText").value = '';
    updateImage();
}

